package mianshi.javabingfa;

/**
 * Synchronized 关键字同步
 */
public class SynchronizedMain {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantLockMain counter = new ReentrantLockMain();

        // 创建多个线程来增加计数器
        Thread[] threads = new Thread[10];
        for (int i = 0; i < threads.length; i++) {
            int threadNum = i;
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    counter.increment();
                }
                System.out.println("Thread " + threadNum + " finished.");
            });
            threads[i].start();
        }

        // 等待所有线程完成
        for (Thread t : threads) {
            t.join();
        }

        // 输出最终的计数器值
        System.out.println("Final count: " + counter.getCount());
    }
}
